﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UIWindow.Attributes;
using UIWindow.Enums;
using UIWindow.Lucifer;
using UIWindow.Models;

namespace UIWindow.Domains
{
    public class ObjectContainer : IObjectContainer
    {
        private List<MenuViewModel> _view = new List<MenuViewModel>();
        private ConcurrentDictionary<string, object> _singletons = new ConcurrentDictionary<string, object>();
        private ConcurrentDictionary<object, object> _event = new ConcurrentDictionary<object, object>();

        public ObjectContainer()
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            var parameter = types.Where(t => t.IsClass && t.Name.Contains("ViewModel")).ToList();
            var page = types.Where(t => t.IsClass && t.GetCustomAttribute<ViewFeatureAttribute>() != null).ToList();
            var singleton = types.Where(t => t.IsClass && t.GetCustomAttribute<SingletonAttribute>() != null).ToList();
            foreach (var item in singleton)
            {
                _singletons.TryAdd(item.Name, Activator.CreateInstance(item));
            }
            foreach (var item in page)
            {
                var vfa = item.GetCustomAttribute<ViewFeatureAttribute>();
                var viewmodel = parameter.Where(t => t.Name == $"{item.Name}ViewModel").FirstOrDefault();
                MenuViewModel viewModel = new MenuViewModel()
                {
                    MenuName = vfa.MenuName,
                    MenuIcon = vfa.MenuIcon,
                    IsSingleton = vfa.IsSingleton,
                    Level = vfa.Level,
                    Index = vfa.Index,
                };
                if (viewModel.IsSingleton)
                {
                    var ps = viewmodel.GetConstructors()[^1].GetParameters();
                    List<object> plist = new List<object>();
                    foreach (var p in ps)
                    {
                        plist.Add(_singletons.ContainsKey(p.ParameterType.Name) ? _singletons[p.ParameterType.Name] : null);
                    }
                    object obj = Activator.CreateInstance(item);
                    (obj as System.Windows.Controls.ContentControl).DataContext = Activator.CreateInstance(viewmodel, plist.ToArray());
                    viewModel.Context = obj;
                }
                else
                {
                    viewModel.View = item;
                    viewModel.ViewModel = viewmodel;
                }
                _view.Add(viewModel);
            }
            _view.Sort((x, y) => x.CompareTo(y));
            var handlerTypes = types.Where(t => t.IsClass && t.GetInterface("ITaskEvent`1") != null).ToList();
            foreach (var handlerType in handlerTypes)
            {
                MethodInfo method = handlerType.GetMethod("Handle");
                var pars = method.GetParameters();
                Type entityType = pars[0].ParameterType;
                var ps = handlerType.GetConstructors()[^1].GetParameters();
                List<object> plist = new List<object>();
                foreach (var p in ps)
                {
                    plist.Add(_singletons.ContainsKey(p.ParameterType.Name) ? _singletons[p.ParameterType.Name] : null);
                }
                var handler = Activator.CreateInstance(handlerType, plist.ToArray());
                _event.TryAdd(entityType, handler);
            }
        }

        public IList<MenuModel> GetMenuList(AuthorityType type) => _view.Where(x => (x.Level & type) != AuthorityType.Null).Select(x => new MenuModel() { Name = x.MenuName, Icon = x.MenuIcon }).ToList();

        public T Resolve<T>() where T : new()
        {
            throw new NotImplementedException();
        }

        public object ResolveEvent(Type type) => _event[type];

        public object ResolvePage(string key)
        {
            var model = _view.FirstOrDefault(x => x.MenuName == key);
            if (model == null) return null;
            if (model.IsSingleton) return model.Context;
            var ps = model.ViewModel.GetConstructors()[^1].GetParameters();
            List<object> plist = new List<object>();
            foreach (var p in ps)
            {
                plist.Add(_singletons.ContainsKey(p.ParameterType.Name) ? _singletons[p.ParameterType.Name] : null);
            }
            object obj = Activator.CreateInstance(model.View);
            (obj as System.Windows.Controls.ContentControl).DataContext = Activator.CreateInstance(model.ViewModel, plist.ToArray());
            return obj;
        }

        public T ResolveSingleton<T>() where T : new() => (T)(_singletons.ContainsKey(typeof(T).Name) ? _singletons[typeof(T).Name] : null);
    }
}
